<?php
class collect extends core {
	private $collect_mod;
	
	public function __construct() {
		parent::__construct();
		$this->collect_mod = m('collect');
	}

	public function index() {
        //查找是否有显示电话号码权限
        $xian = SQL::share('admin_permission')->where("app='all' AND act='phone' AND admin_id='{$this->admin_id}'")->row();
		$where = '';
		$aa = $this->request->get('aa');
		if ($aa=='zz') {
			$rs = SQL::share('collect')->sort('id ASC')->find('id');
			if ($rs) {
				foreach ($rs as $k=>$g) {
					$this->collect_mod->set_collect_month($g->id);
				}
			}
			echo 'ok';exit;
		}
		$id = $this->request->get('id');
		$export = $this->request->get('export', 0);
		//$keyword = $this->request->get('keyword');
		$city_id = $this->request->get('city_id');
		$member_type = urldecode($this->request->get('member_type'));
		$member_name = urldecode($this->request->get('member_name'));
		$real_name = urldecode($this->request->get('real_name'));
		$idcard = urldecode($this->request->get('idcard'));
		$social_number = $this->request->get('social_number');
		$gjj_number = $this->request->get('gjj_number');
		$person_type = urldecode($this->request->get('person_type'));
		$mobile = $this->request->get('mobile');
		$month = $this->request->get('month');
		$gmonth = $this->request->get('gmonth');
		$remark1 = urldecode($this->request->get('remark1'));
		$remark2 = urldecode($this->request->get('remark2'));
		$status = $this->request->get('status');
		$kstatus = $this->request->get('kstatus');
		$gstatus = $this->request->get('gstatus');
		$gkstatus = $this->request->get('gkstatus');
		$pagesize = $this->request->get('pagesize',50);
		if ($pagesize<=0) $pagesize=50;
		/*if ($keyword) {
			$where .= " AND (cl.member_name LIKE '%{$keyword}%' OR cl.real_name LIKE '%{$keyword}%' OR cl.idcard LIKE '%{$keyword}%'
			OR cl.social_number LIKE '%{$keyword}%' OR cl.mobile LIKE '%{$keyword}%' OR cl.remark1 LIKE '%{$keyword}%' OR cl.remark2 LIKE '%{$keyword}%')";
		}*/
		if (strlen($id>0)) {
			$where .= " AND cl.id='{$id}'";
		}
		if (strlen($city_id)) {
			$where .= " AND cl.city_id='{$city_id}'";
		}
		if (strlen($member_type)) {
			$where .= " AND cl.member_type='{$member_type}'";
		}
		if (strlen($member_name)) {
			$where .= " AND cl.member_name LIKE '%{$member_name}%'";
		}
		if (strlen($real_name)) {
			$where .= " AND cl.real_name LIKE '%{$real_name}%'";
		}
		if (strlen($idcard)) {
			$where .= " AND cl.idcard LIKE '%{$idcard}%'";
		}
		if (strlen($social_number)) {
			$where .= " AND cl.social_number LIKE '%{$social_number}%'";
		}
		if (strlen($gjj_number)) {
			$where .= " AND cl.gjj_number LIKE '%{$gjj_number}%'";
		}
		if (strlen($person_type)) {
			$where .= " AND cl.person_type LIKE '%{$person_type}%'";
		}
		if (strlen($mobile)) {
			$where .= " AND cl.mobile LIKE '%{$mobile}%'";
		}
		if (strlen($month)) {
			$where .= " AND cl.month LIKE '%{$month}%'";
		}
		if (strlen($gmonth)) {
			$where .= " AND cl.gmonth LIKE '%{$gmonth}%'";
		}
		if (strlen($remark1)) {
			$where .= " AND cl.remark1 LIKE '%{$remark1}%'";
		}
		if (strlen($remark2)) {
			$where .= " AND cl.remark2 LIKE '%{$remark2}%'";
		}
		if (strlen($status)) {
			$where .= " AND cl.status='{$status}'";
		}
		if (strlen($kstatus)) {
			$where .= " AND cl.kstatus='{$kstatus}'";
		}
		if (strlen($gstatus)) {
			$where .= " AND cl.gstatus='{$gstatus}'";
		}
		if (strlen($gkstatus)) {
			$where .= " AND cl.gkstatus='{$gkstatus}'";
		}
		$print_all = $this->request->get('print_all');
		// if ($print_all) {
		// 	$pagesize = 100000;
		// } else {
		// 	$pagesize = 50;
		// }
		// echo $where;
		// echo $member_type;

        $num = SQL::share('collect')->count();
        $e = 0;
        if ($export>0){
            set_time_limit(0);
            ini_set ('memory_limit', '512M');
            for($i=1500;$i<$num;$i++)
            {
                $e += $i;
                if ($e>=$num){
                    break;
                }
                $arr[] = $i;
                $n = count($arr);
            }
            $total = array();
            for ($page=0;$page<=$n;$page++){
                $rs = SQL::share('collect cl')
                    ->left('admin a', 'cl.admin_id=a.id')
                    ->left('city c', 'c.city_id=cl.city_id')
                    ->left('service_casy s', 'cl.casy_id=s.id')
                    ->where($where)->order('id DESC')->limit(1500*$page, 1500)
                    ->setpages(compact('id', 'city_id', 'member_type', 'member_name', 'real_name', 'idcard', 'social_number', 'gjj_number',
                        'person_type', 'mobile', 'month', 'gmonth', 'remark1', 'remark2', 'status', 'kstatus', 'gstatus', 'gkstatus', 'pagesize'))
                    ->find("cl.*, c.name as city_name, a.real_name as admin_name, '' as end_date, s.name as casy_name");
                if ($rs){
                    foreach ($rs as $k => $g){
                        $rs[$k]->begin_time = date('Y-m-d',$g->begin_time);
                        if (empty($xian)){
                            $xing = substr($g->mobile,4,4);  //获取手机号中间四位
                            $rs[$k]->mobile = str_replace($xing,'****',$g->mobile);  //用****进行替换
                        }
                    }
                }

                if (!empty($rs)){
                    $total = array_merge($rs, $total);
                }
                if ($total){
                    foreach ($total as $k=>$g){
                        $total[$k]->idcard = $g->idcard."\t";
                        $total[$k]->mobile = $g->mobile."\t";
                        $total[$k]->social_number = $g->social_number."\t";
                        $total[$k]->gjj_number = $g->gjj_number."\t";
                        $total[$k]->month = $g->month."\t";
                        $total[$k]->gmonth = $g->gmonth."\t";
                        $total[$k]->remark1 = $g->remark1."\t";
                        $total[$k]->remark2 = $g->remark2."\t";
                        $total[$k]->begin_time = $g->begin_time."\t";
                        $total[$k]->member_name = $g->member_name."\t";
                    }
                }
            }
            $total = object_to_array($total);
            if ($total){
                foreach ($total as $k=>$g){
                    $total[$k]['status'] = $this->collect_mod->n_status($g['status']);
                    $total[$k]['gstatus'] = $this->collect_mod->n_gstatus($g['gstatus']);
                    $total[$k]['kstatus'] = $this->collect_mod->n_kstatus($g['kstatus']);
                    $total[$k]['gkstatus'] = $this->collect_mod->n_gkstatus($g['gkstatus']);

                    //找出这个月之前的月份数量
                    $months = SQL::share('collect_month')->where("collect_id='{$g['id']}' AND type=0")
                        ->comparenow('m', "CONCAT(month,'-1')", '<=0', "DATE_FORMAT(NOW(),'%Y-%m-1')")->count();
                    //echo $months;exit;
                    // print_r(SQL::sqls);exit;
                    $total_price = ($g['social_price']+$g['service_price'])*$months;
                    $months = SQL::share('collect_month')->where("collect_id='{$g['id']}' AND type=1")
                        ->comparenow('m', "CONCAT(month,'-1')", '<=0', "DATE_FORMAT(NOW(),'%Y-%m-1')")->count();
                    $total_price += ($g['gjj_price']+$g['gjj_service_price'])*$months;
                    $total[$k]['total_price'] = number_format(round($total_price,2),2,'.','');
                }
            }
        }else{

            $rs = SQL::share('collect cl')
                ->left('admin a', 'cl.admin_id=a.id')
                ->where($where)->sort('cl.id DESC')->isezr()->pagesize($export>0?99999:$pagesize)
                ->setpages(compact('id', 'city_id', 'member_type', 'member_name', 'real_name', 'idcard', 'social_number', 'gjj_number',
                    'person_type', 'mobile', 'month', 'gmonth', 'remark1', 'remark2', 'status', 'kstatus', 'gstatus', 'gkstatus', 'pagesize'))
                ->find("cl.*, '' as city_name, a.real_name as admin_name, '' as end_date, '' as casy_name");

            $recordpage = SQL::share()->page;

            if ($rs) {
                foreach ($rs as $k=>$g) {
                    if ($g->casy_id>0) $rs[$k]->casy_name = SQL::share('service_casy')->where($g->casy_id)->val('name');
                    if ($g->city_id>0) {
                        $rs[$k]->city_name = SQL::share('city')->where("city_id='{$g->city_id}'")->val('name');
                        $rs[$k]->city_name = str_replace('市', '', $rs[$k]->city_name);
                    }
                    $rs[$k]->begin_date = date('Y-m-d', $g->begin_time);
                    $rs[$k]->end_date = date('Y-m-d', $g->end_time);
                    $rs[$k]->status = $this->collect_mod->status_name($g->status);
                    $rs[$k]->kstatus = $this->collect_mod->kstatus_name($g->kstatus);
                    $rs[$k]->gstatus = $this->collect_mod->gstatus_name($g->gstatus);
                    $rs[$k]->gkstatus = $this->collect_mod->gkstatus_name($g->gkstatus);
                    //SELECT count(*) FROM hq_collect_month WHERE collect_id='8' AND type=0 AND TIMESTAMPDIFF(MONTH,CONCAT(month,'-1'),DATE_FORMAT(NOW(),'%Y-%m-1'))<=0
                    //找出这个月之前的月份数量
                    $months = SQL::share('collect_month')->where("collect_id='{$g->id}' AND type=0")
                        ->comparenow('m', "CONCAT(month,'-1')", '<=0', "DATE_FORMAT(NOW(),'%Y-%m-1')")->count();
                    //echo $months;exit;
                    // print_r(SQL::sqls);exit;
                    $total_price = ($g->social_price+$g->service_price)*$months;
                    $months = SQL::share('collect_month')->where("collect_id='{$g->id}' AND type=1")
                        ->comparenow('m', "CONCAT(month,'-1')", '<=0', "DATE_FORMAT(NOW(),'%Y-%m-1')")->count();
                    $total_price += ($g->gjj_price+$g->gjj_service_price)*$months;
                    $rs[$k]->total_price = number_format(round($total_price,2),2,'.','');
                    if (empty($xian)){
                        $xing = substr($g->mobile,4,4);  //获取手机号中间四位
                        $rs[$k]->mobile = str_replace($xing,'****',$g->mobile);  //用****进行替换
                    }
                }
            }
        }
		if ($export>0) {
		    $name = generate_order_sn();
            exportCommon($total, array(
                'id'=>'ID',
				'city_name'=>'城市',
				'member_type'=>'支付渠道',
				'member_name'=>'账号',
				'begin_time'=>'首次缴费日期',
				'real_name'=>'姓名',
				'idcard'=>'身份证',
				'social_number'=>'社保号',
				'gjj_number'=>'公积金账号',
				'person_type'=>'户口性质',
				'mobile'=>'联系电话',
				'casy_name'=>'社保档次',
				'social_price'=>'社保费',
				'gjj_price'=>'公积金',
				'service_price'=>'社保服务费',
				'gjj_service_price'=>'公积金服务费',
				'total_price'=>'合计缴费',
				'month'=>'社保缴费月份',
				'gmonth'=>'公积金缴费月份',
                'remark1'=>'备注1',
				'remark2'=>'备注2',
				'status'=>'社保增员状态',
				'kstatus'=>'社保扣费状态',
				'gstatus'=>'公积金增员状态',
				'gkstatus'=>'公积金扣费状态'
			), $name);
		}else{
            $this->smarty->assign('rs', $rs);
            $this->smarty->assign('page', $recordpage);
            $this->smarty->assign('city', $this->collect_mod->get_city());
            $this->smarty->assign('status_list', $this->collect_mod->status());
            $this->smarty->assign('kstatus_list', $this->collect_mod->kstatus());
            $this->smarty->assign('gstatus_list', $this->collect_mod->gstatus());
            $this->smarty->assign('gkstatus_list', $this->collect_mod->gkstatus());
            // if ($print_all) {
            // $this->display('collect.print_all.html');
            // } else {
            $this->display();
            // }
        }
	}
	
	private function is_idcard($idcard) {
		if (strlen($idcard)==18) {
			return true;
		} else {
			return false;
		}
		$idcard_verify_number = function($idcard_base) {
			//计算身份证校验码，根据国家标准GB 11643-1999
			if (strlen($idcard_base)!=17) return false;
			$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //加权因子
			$verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); //校验码对应值
			$checksum = 0;
			for ($i=0; $i<strlen($idcard_base); $i++) {
				$checksum += substr($idcard_base,$i,1) * $factor[$i];
			}
			$mod = $checksum % 11;
			$verify_number = $verify_number_list[$mod];
			return $verify_number;
		};
		$idcard_15to18 = function($idcard) use($idcard_verify_number) {
			//将15位身份证升级到18位
			if (strlen($idcard)!=15) return false;
			//如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
			if (array_search(substr($idcard,12,3), array('996','997','998','999')) !== false) {
				$idcard = substr($idcard,0,6).'18'.substr($idcard,6,9);
			} else {
				$idcard = substr($idcard,0,6).'19'.substr($idcard,6,9);
			}
			$idcard = $idcard.$idcard_verify_number($idcard);
			return $idcard;
		};
		$idcard_checksum18 = function($idcard) use($idcard_verify_number) {
			//18位身份证校验码有效性检查
			if (strlen($idcard)!=18) return false;
			$idcard_base = substr($idcard,0,17);
			if ($idcard_verify_number($idcard_base) != strtoupper(substr($idcard,17,1))) {
				return false;
			} else {
				return true;
			}
		};
		if (strlen($idcard)==18) {
			return $idcard_checksum18($idcard);
		} else if (strlen($idcard)==15) {
			$idcard = $idcard_15to18($idcard);
			return $idcard_checksum18($idcard);
		} else {
			return false;
		}
	}
	private function is_mobile($mobile) {
		return preg_match('/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$/', $mobile) ? true : false;
	}
	private function is_tel($tel) {
		return preg_match('/^((\d{3,4}-)?\d{8}(-\d+)?|(\(\d{3,4}\))?\d{8}(-\d+)?)$/', $tel) ? true : false;
	}
	private function is_phone($phone) {
		if ($phone && is_numeric($phone)) {
			return true;
		} else {
			return false;
		} 
		// $result = $this->is_mobile($phone);
		// if (!$result) $result = $this->is_tel($phone);
		// return $result;
	}
	private function is_date($date) {
		return preg_match('/^(?:(?!0000)[0-9]{4}[\/-](?:(?:0?[1-9]|1[0-2])[\/-](?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])[\/-](?:29|30)|(?:0?[13578]|1[02])[\/-]31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)[\/-]0?2[\/-]29)$/', $date) ? true : false;
	}
	private function is_months($months) {
		$months = str_replace("，", ",", $months);
		return preg_match('/^\d{4}\-\d{1,2}([,]\d{4}\-\d{1,2})*$/', $months) ? true : false;
	}
	public function check_cate() {
		$checkbox = $this->request->post('checkbox', '', 'origin');
		$cate_type = $this->request->post('cate_type');
		if ($cate_type=='import') {
			$file = upload_one_file('collect', 'file', false, false, false);
			if (!strlen($file)) error('文件错误，请重新上传');
			$datas = import_excel($file, 0, 2);
			if (!count($datas)) error('文件没有任何数据，请重新上传');
			$memberTypes = array('本站', '淘宝欢创总店', '天猫总店', '淘宝广州社保代缴店', '转到公账');
			$personTypes = array('本地城镇', '本地农村', '外地城镇', '外地农村');
			$success = array();
			$error = array();
			foreach ($datas as $k=>$g) {
				$d = new stdClass();
				
				$city = SQL::share('service_city sc')->left('city c', 'sc.city_id=c.city_id')->where("c.name LIKE '%".trim($g['A'])."%'")->row();
				if (!$city) {
					$g['row'] = $k;
					$g['error'] = '城市错误';
					$error[] = $g;
					continue;
				}
				$d->city_id = $city->city_id;
				$d->city_name = $city->name;
				$member_type = trim($g['B']);
				if (!in_array($member_type, $memberTypes)) {
					$g['row'] = $k;
					$g['error'] = '付款渠道错误';
					$error[] = $g;
					continue;
				}
				$d->member_type = $member_type;
				$member_name = trim($g['C']);
				if (!strlen($member_name)) {
					$g['row'] = $k;
					$g['error'] = '账号错误';
					$error[] = $g;
					continue;
				}
				$d->member_name = $member_name;
				$begin_time = trim($g['D']);
				if (!$this->is_date($begin_time)) {
					$g['row'] = $k;
					$g['error'] = '首次缴费日期错误';
					$error[] = $g;
					continue;
				}
				$begin_time = strtotime($begin_time);
				$d->begin_date = date('Y-m-d', $begin_time);
				$d->begin_time = $begin_time;
				// $et = str_replace('/', '-', trim($g['E']));
				// $et = explode('-', $et);
				// if (count($et)<2) {
				// 	$g['row'] = $k;
				// 	$g['error'] = '到期时间错误';
				// 	$error[] = $g;
				// 	continue;
				// }
				// $end_time = strtotime($et[0].'-'.$et[1].'-01 +1 month -1 day');
				// $d->end_date = date('Y-m-d', $end_time);
				// $d->end_time = $end_time;
				$real_name = trim($g['E']);
				if (!strlen($real_name)) {
					$g['row'] = $k;
					$g['error'] = '姓名错误';
					$error[] = $g;
					continue;
				}
				$d->real_name = $real_name;
				$idcard = trim($g['F']);
				if (!$this->is_idcard($idcard)) {
					$g['row'] = $k;
					$g['error'] = '身份证错误';
					$error[] = $g;
					continue;
				}
				$d->idcard = $idcard;
				$social_number = trim($g['G']);
				// if (!strlen($social_number)) {
				// 	$g['row'] = $k;
				// 	$g['error'] = '社保账号错误';
				// 	$error[] = $g;
				// 	continue;
				// }
				$d->social_number = $social_number;
				$gjj_number = trim($g['H']);
				// if (strlen($gjj_number)) {
				// 	$g['row'] = $k;
				// 	$g['error'] = '公积金账号错误';
				// 	$error[] = $g;
				// 	continue;
				// }
				$d->gjj_number = $gjj_number;
				$person_type = trim($g['I']);
				if (!in_array($person_type, $personTypes)) {
					$g['row'] = $k;
					$g['error'] = '户口性质错误';
					$error[] = $g;
					continue;
				}
				$d->person_type = $person_type;
				$mobile = trim($g['J']);
				if (!$this->is_phone($mobile)) {
					$g['row'] = $k;
					$g['error'] = '电话号码错误';
					$error[] = $g;
					continue;
				}
				$d->mobile = $mobile;
				$casy_name = trim($g['K']);
				if (!strlen($casy_name)) {
					$g['row'] = $k;
					$g['error'] = '社保档次错误';
					$error[] = $g;
					continue;
				}
				$casy = SQL::share('service_casy')->where("name='{$casy_name}'")->row();
				if (!$casy) {
					$g['row'] = $k;
					$g['error'] = '社保档次错误';
					$error[] = $g;
					continue;
				}
				$d->casy_name = $casy_name;
				$d->casy_id = $casy->id;
				$social_price = is_numeric(trim($g['L'])) ? floatval(trim($g['L'])) : 0;
				if (floatval($social_price)<=0) {
					$g['row'] = $k;
					$g['error'] = '社保费用错误';
					$error[] = $g;
					continue;
				}
				$d->social_price = $social_price;
				$gjj_price = is_numeric(trim($g['M'])) ? floatval(trim($g['M'])) : 0;
				if (!is_numeric($gjj_price)) {
					$g['row'] = $k;
					$g['error'] = '公积金费用错误';
					$error[] = $g;
					continue;
				}
				$d->gjj_price = $gjj_price;
				$service_price = is_numeric(trim($g['N'])) ? floatval(trim($g['N'])) : 0;
				if (floatval($service_price)<0) {
					$g['row'] = $k;
					$g['error'] = '社保服务费错误';
					$error[] = $g;
					continue;
				}
				$d->service_price = $service_price;
				$gjj_service_price = is_numeric(trim($g['O'])) ? floatval(trim($g['O'])) : 0;
				if (!is_numeric($gjj_service_price)) {
					$g['row'] = $k;
					$g['error'] = '公积金服务费错误';
					$error[] = $g;
					continue;
				}
				$d->gjj_service_price = $gjj_service_price;
				$total_price = is_numeric(trim($g['P'])) ? floatval(trim($g['P'])) : 0;
				if (floatval($total_price)<0) {
					$g['row'] = $k;
					$g['error'] = '合计费用错误';
					$error[] = $g;
					continue;
				}
				$d->total_price = $total_price;
				//$admin = SQL::share('admin')->where("real_name='" . trim($g['O']) . "'")->val('id');
				//if ($admin == NULL) $admin = SQL::share('admin')->where("id>1")->sort('id ASC')->val('id');
				//$admin_id = $admin;
				//$admin_id = 1;
				$month = trim($g['Q']);
				if (!$this->is_months($month)) {
					$g['row'] = $k;
					$g['error'] = '社保缴费月份错误';
					$error[] = $g;
					continue;
				}
				$d->month = $month;
				$gmonth = trim($g['R']);
				if (strlen($gmonth) && !$this->is_months($gmonth)) {
					$g['row'] = $k;
					$g['error'] = '公积金缴费月份错误';
					$error[] = $g;
					continue;
				}
				$d->gmonth = $gmonth;
				$remark1 = trim($g['S']);
				$d->remark1 = $remark1;
				$remark2 = trim($g['T']);
				$d->remark2 = $remark2;
				$s = array_search(trim($g['U']), $this->collect_mod->status());
				if ($s===false) {
					$g['row'] = $k;
					$g['error'] = '社保增员状态错误';
					$error[] = $g;
					continue;
				}
				$status = $s !== false ? $s : 0;
				$d->status_name = trim($g['U']);
				$d->status = $status;
				$ks = array_search(trim($g['V']), $this->collect_mod->kstatus());
				if ($ks===false) {
					$g['row'] = $k;
					$g['error'] = '社保扣费状态错误';
					$error[] = $g;
					continue;
				}
				$kstatus = $ks !== false ? $ks : 0;
				$d->kstatus_name = trim($g['V']);
				$d->kstatus = $kstatus;
				$gs = array_search(trim($g['W']), $this->collect_mod->gstatus());
				if ($gs===false) {
					$g['row'] = $k;
					$g['error'] = '公积金增员状态错误';
					$error[] = $g;
					continue;
				}
				$gstatus = $gs !== false ? $gs : 0;
				$d->gstatus_name = trim($g['W']);
				$d->gstatus = $gstatus;
				$gks = array_search(trim($g['X']), $this->collect_mod->gkstatus());
				if ($gks===false) {
					$g['row'] = $k;
					$g['error'] = '公积金扣费状态错误';
					$error[] = $g;
					continue;
				}
				$gkstatus = $gks !== false ? $gks : 0;
				$d->gkstatus_name = trim($g['X']);
				$d->gkstatus = $gkstatus;
				/*
				$data = compact('city_id', 'member_type', 'member_name', 'begin_time', 'end_time', 'real_name', 'idcard', 'social_number', 'gjj_number', 'person_type',
					'mobile', 'social_price', 'gjj_price', 'service_price', 'total_price', 'admin_id', 'month', 'gmonth', 'remark1', 'remark2', 'status', 'kstatus',
					'gstatus', 'gkstatus');
				
				$row = NULL;
				if (strlen($city_id) && strlen($idcard)) {
					$row = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->row('id');
				}
				if ($row) {
					SQL::share('collect')->where($row->id)->update($data);
				} else {
					$data['add_time'] = time();
					SQL::share('collect')->insert($data);
				}
				*/
				$d->row = $k;
				$success[] = $d;
			}
			$_SESSION['collect.import'] = $success;
			$this->smarty->assign('data', array('success'=>$success, 'error'=>$error));
			$this->display('collect.import.html');
			exit;
		/*
		} else if (is_array($checkbox)) {
			$ids = implode(',', $checkbox);
			switch ($cate_type) {
				case 'remark1':
					$remark1 = $this->request->post('remark1');
					SQL::share('collect')->where("id IN ({$ids})")->update(array('remark1'=>$remark1));
					break;
				case 'remark2':
					$remark2 = $this->request->post('remark2');
					SQL::share('collect')->where("id IN ({$ids})")->update(array('remark2'=>$remark2));
					break;
				case 'status':
					$status = $this->request->post('status', 0);
					SQL::share('collect')->where("id IN ({$ids})")->update(array('status'=>$status));
					break;
			}
		}
		*/
		} else {
			$where = '';
			$id = $this->request->post('id');
			$city_id = $this->request->post('city_id');
			$member_type = $this->request->post('member_type');
			$member_name = $this->request->post('member_name');
			$real_name = $this->request->post('real_name');
			$idcard = $this->request->post('idcard');
			$social_number = $this->request->post('social_number');
			$gjj_number = $this->request->post('gjj_number');
			$person_type = $this->request->post('person_type');
			$mobile = $this->request->post('mobile');
			$month = $this->request->post('month');
			$gmonth = $this->request->post('gmonth');
			$remark1 = $this->request->post('remark1');
			$remark2 = $this->request->post('remark2');
			$status = $this->request->post('status');
			$kstatus = $this->request->post('kstatus');
			$gstatus = $this->request->post('gstatus');
			$gkstatus = $this->request->post('gkstatus');
			if (strlen($id>0)) {
				$where .= " AND cl.id='{$id}'";
			}
			if (strlen($city_id)) {
				$where .= " AND cl.city_id='{$city_id}'";
			}
			if (strlen($member_type)) {
				$where .= " AND cl.member_type LIKE '%{$member_type}%'";
			}
			if (strlen($member_name)) {
				$where .= " AND cl.member_name LIKE '%{$member_name}%'";
			}
			if (strlen($real_name)) {
				$where .= " AND cl.real_name LIKE '%{$real_name}%'";
			}
			if (strlen($idcard)) {
				$where .= " AND cl.idcard LIKE '%{$idcard}%'";
			}
			if (strlen($social_number)) {
				$where .= " AND cl.social_number LIKE '%{$social_number}%'";
			}
			if (strlen($gjj_number)) {
				$where .= " AND cl.gjj_number LIKE '%{$gjj_number}%'";
			}
			if (strlen($person_type)) {
				$where .= " AND cl.person_type LIKE '%{$person_type}%'";
			}
			if (strlen($mobile)) {
				$where .= " AND cl.mobile LIKE '%{$mobile}%'";
			}
			if (strlen($month)) {
				$where .= " AND cl.month LIKE '%{$month}%'";
			}
			if (strlen($gmonth)) {
				$where .= " AND cl.gmonth LIKE '%{$gmonth}%'";
			}
			if (strlen($remark1)) {
				$where .= " AND cl.remark1 LIKE '%{$remark1}%'";
			}
			if (strlen($remark2)) {
				$where .= " AND cl.remark2 LIKE '%{$remark2}%'";
			}
			if (strlen($status)) {
				$where .= " AND cl.status='{$status}'";
			}
			if (strlen($kstatus)) {
				$where .= " AND cl.kstatus='{$kstatus}'";
			}
			if (strlen($gstatus)) {
				$where .= " AND cl.gstatus='{$gstatus}'";
			}
			if (strlen($gkstatus)) {
				$where .= " AND cl.gkstatus='{$gkstatus}'";
			}
			$ids = array();
			// echo "where:{$where}";exit;
			SQL::share()->log = true;
			$rs = SQL::share('collect cl')
				->left('city c', 'cl.city_id=c.city_id')
				->where($where)->sort('cl.id DESC')->isezr()->pagesize(999999)
				->find("cl.id");
			// echo SQL::share()->log();exit;
			if (!$rs) error('暂无对应记录');
			foreach ($rs as $k=>$g) {
				$ids[] = $g->id;
			}
			$ids = implode(',', $ids);
			switch ($cate_type) {
				case 'remark1':
					$remark1 = $this->request->post('modal_remark1');
					SQL::share('collect')->where("id IN ({$ids})")->update(array('remark1'=>$remark1));
					break;
				case 'remark2':
					$remark2 = $this->request->post('modal_remark2');
					SQL::share('collect')->where("id IN ({$ids})")->update(array('remark2'=>$remark2));
					break;
				case 'status':
					$status = $this->request->post('modal_status');
					$kstatus = $this->request->post('modal_kstatus');
					$gstatus = $this->request->post('modal_gstatus');
					$gkstatus = $this->request->post('modal_gkstatus');
					if (strlen($status)){
						SQL::share('collect')->where("id IN ({$ids})")->update(compact('status'));
					}
					if (strlen($kstatus)){
						SQL::share('collect')->where("id IN ({$ids})")->update(compact('kstatus'));
					}
					if (strlen($gstatus)){
						SQL::share('collect')->where("id IN ({$ids})")->update(compact('gstatus'));
					}
					if (strlen($gkstatus)){
						SQL::share('collect')->where("id IN ({$ids})")->update(compact('gkstatus'));
					}
					// echo "status:{$status}<br>";
					// echo "kstatus:{$kstatus}<br>";
					// echo "gstatus:{$gstatus}<br>";
					// echo "gkstatus:{$gkstatus}<br>";
					// exit;
					// SQL::share('collect')->where("id IN ({$ids})")->update(compact('status', 'kstatus', 'gstatus', 'gkstatus'));
					break;
			}
		}
		location("?app=collect&act=index");
	}
	
	//保存导入
	public function import() {
		$success = $this->request->session('collect.import', '', 'origin');
		if (!$success || !is_array($success)) error('缺少数据');
		foreach ($success as $k=>$g) {
			$data = array('city_id'=>$g->city_id, 'member_type'=>$g->member_type, 'member_name'=>$g->member_name, 'begin_time'=>$g->begin_time, 'end_time'=>$g->end_time,
				'real_name'=>$g->real_name, 'idcard'=>$g->idcard, 'social_number'=>$g->social_number, 'gjj_number'=>$g->gjj_number, 'person_type'=>$g->person_type,
				'mobile'=>$g->mobile, 'social_price'=>$g->social_price, 'gjj_price'=>$g->gjj_price, 'service_price'=>$g->service_price, 'gjj_service_price'=>$g->gjj_service_price, 'total_price'=>$g->total_price,
				'admin_id'=>1, 'month'=>$g->month, 'gmonth'=>$g->gmonth, 'casy_id'=>$g->casy_id, 'remark1'=>$g->remark1, 'remark2'=>$g->remark2,
				'status'=>$g->status, 'kstatus'=>$g->kstatus, 'gstatus'=>$g->gstatus, 'gkstatus'=>$g->gkstatus);
			$row = SQL::share('collect')->where("city_id='{$g->city_id}' AND idcard='{$g->idcard}'")->row('id');
			if ($row) {
				SQL::share('collect')->where($row->id)->update($data);
				$id = $row->id;
			} else {
				$data['add_time'] = time();
				$id = SQL::share('collect')->insert($data);
			}
			$this->collect_mod->set_collect_month($id);
		}
		$_SESSION['collect.import'] = '';
		success('ok', '成功', 0, NULL, '?app=collect&act=index', '提交成功');
	}
	
	//保存隐藏列
	public function save_column() {
		$ids = $this->request->post('ids');
		SQL::share('admin')->where($this->admin_id)->update(array('hidden_columns'=>$ids));
		success('ok');
	}
	
	public function edit() {
		$id = $this->request->get('id', 0);
        //查找是否有显示电话号码权限
        $xian = SQL::share('admin_permission')->where("app='all' AND act='phone' AND admin_id='{$this->admin_id}'")->row();
		if (IS_POST) {
			$id = $this->request->post('id', 0);
			$city_id = $this->request->post('city_id', 0);
			$member_type = $this->request->post('member_type');
			$member_name = $this->request->post('member_name');
			$begin_time = $this->request->post('begin_time');
			$end_time = $this->request->post('end_time');
			$real_name = $this->request->post('real_name');
			$idcard	= $this->request->post('idcard');
			$social_number = $this->request->post('social_number');
			$gjj_number = $this->request->post('gjj_number');
			$person_type = $this->request->post('person_type');
			$mobile = $this->request->post('mobile');
			$casy_id = $this->request->post('casy_id', 0);
			$social_price = $this->request->post('social_price', 0, 'float');
			$gjj_price = $this->request->post('gjj_price', 0, 'float');
			$service_price = $this->request->post('service_price', 0, 'float');
			$gjj_service_price = $this->request->post('gjj_service_price', 0, 'float');
			$total_price = $this->request->post('total_price', 0, 'float');
			$admin_id = $this->request->post('admin_id', 1);
			$begin_month = $this->request->post('begin_month');
			$end_month = $this->request->post('end_month');
			$begin_gmonth = $this->request->post('begin_gmonth');
			$end_gmonth = $this->request->post('end_gmonth');
			$remark1 = $this->request->post('remark1');
			$remark2 = $this->request->post('remark2');
			$status	= $this->request->post('status', 0);
			$kstatus = $this->request->post('kstatus', 0);
			$gstatus = $this->request->post('gstatus', 0);
			$gkstatus = $this->request->post('gkstatus', 0);
			$begin_time = strtotime($begin_time);

            $old_mobile = SQL::share('collect')->where("id='{$id}'")->val('mobile');

            if ($mobile != $old_mobile){
                $x_mobile =  strstr($mobile, '*');
                if ($x_mobile){
                    $mobile = $old_mobile;
                }
            }
			//$end_time = strtotime($end_time);
			$month = $this->collect_mod->getMonthRange($begin_month.'-1', $end_month.'-1');
			$gmonth = array();
			if (strlen($begin_gmonth) && strlen($end_gmonth)) $gmonth = $this->collect_mod->getMonthRange($begin_gmonth.'-1', $end_gmonth.'-1');
			$end_time = strtotime($month[count($month)-1]);
			if ($id) {
				//$c = SQL::share('collect')->where($id)->row('month, gmonth');
				//$months = explode(',', str_replace('，', ',', $c->month));
				//$month = array_merge($month, $months);
				$month = $this->collect_mod->sortMonths($month);
				
				//$gmonths = explode(',', str_replace('，', ',', $c->gmonth));
				//$gmonth = array_merge($gmonth, $gmonths);
				$gmonth = $this->collect_mod->sortMonths($gmonth);
			}
			// $month = implode('，', $month);
			// $gmonth = implode('，', $gmonth);
			$month = implode(',', $month);
			$gmonth = implode(',', $gmonth);
			$data = compact('city_id', 'member_type', 'member_name', 'begin_time', 'end_time', 'real_name', 'idcard',
				'social_number', 'gjj_number', 'person_type', 'mobile', 'casy_id', 'social_price', 'gjj_price',
				'service_price', 'gjj_service_price', 'total_price', 'admin_id', 'month', 'gmonth', 'remark1', 'remark2',
				'status', 'kstatus', 'gstatus', 'gkstatus');
			if ($id) {
			    //先检查city_id和idcard有无变化
                $rs = SQL::share('collect')->where("id='{$id}'")->row('city_id, idcard');
                if ($rs->city_id!=$city_id || $rs->idcard!=$idcard){
                    //有变化就要判断
                    $count = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->count();
                    if ($count>0) error("该城市下的身份证{$idcard}已存在");
                }
				SQL::share('collect_month')->delete("collect_id='{$id}'");
				SQL::share('collect')->where($id)->update($data);
			} else {
				$count = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->count();
				if ($count>0) error("该城市下的身份证{$idcard}已存在");
				$data['add_time'] = time();
				$id = SQL::share('collect')->insert($data);
			}
			$this->collect_mod->set_collect_month($id);
			if (isset($_SESSION['collect_redirect']) && stripos($_SESSION['collect_redirect'], 'pp=collect&act=index')) {
				$redirect = $_SESSION['collect_redirect'];
				$_SESSION['collect_redirect'] = "";
				location($redirect);	
			} else {
				location("?app=collect&act=edit&id={$id}&msg=1");
			}
		} else if ($id>0) {
			$row = SQL::share('collect')->where($id)->row("*, '' as begin_month, '' as end_month, '' as begin_gmonth, '' as end_gmonth");
			if ($row) {
                if (empty($xian)){
                    $xing = substr($row->mobile,4,4);  //获取手机号中间四位
                    $row->mobile = str_replace($xing,'****',$row->mobile);  //用****进行替换
                }
				if (strlen($row->month)) {
					$months = explode('，', $row->month);
					if (strpos($row->month,',')!==false) $months = explode(',', $row->month);
					$row->begin_month = $months[0];
					$row->end_month = $months[count($months)-1];
				}
				if (strlen($row->gmonth)) {
					$gmonths = explode('，', $row->gmonth);
					if (strpos($row->gmonth,',')!==false) $gmonths = explode(',', $row->gmonth);
					$row->begin_gmonth = $gmonths[0];
					$row->end_gmonth = $gmonths[count($gmonths)-1];
				}
			}
		} else {
			$row = t('collect');
			$row->begin_time = time();
			$row->begin_month = '';
			$row->end_month = '';
			$row->begin_gmonth = '';
			$row->end_gmonth = '';
		}
		$this->smarty->assign('row', $row);
		$this->smarty->assign('status', $this->collect_mod->status());
		$this->smarty->assign('kstatus', $this->collect_mod->kstatus());
		$this->smarty->assign('gstatus', $this->collect_mod->gstatus());
		$this->smarty->assign('gkstatus', $this->collect_mod->gkstatus());
		$this->smarty->assign('city', $this->collect_mod->get_city());
		$this->smarty->assign('manager', SQL::share('admin')->where("id>1 AND status=1")->sort('id ASC')->find('id, real_name'));
		$_SESSION['collect_redirect'] = $_SERVER['HTTP_REFERER'];
		$this->display();
	}
	
	public function delete() {
		$id = $this->request->get('id', 0);
		// $this->permission($this->admin_id, $this->app, $this->act);
		SQL::share('collect')->delete($id);
		SQL::share('collect_month')->delete("collect_id='{$id}'");
		location("?app=collect&act=index");
	}
	
	//参保方案
	public function get_casy() {
		$city_id = $this->request->get('city_id', 0);
		if ($city_id<=0) error('数据错误');
		$rs = SQL::share('service_casy sa')
			->left('service_city sc', 'service_city_id=sc.id')
			->where("sc.city_id='{$city_id}'")->sort('sa.id ASC')->find('sa.*');
		success($rs);
	}
	
	public function log() {
		$where = '';
		$content = $this->request->get('content');
		$ip = $this->request->get('ip');
		if ($content) {
			$where .= " AND content LIKE '%{$content}%'";
		}
		if ($ip) {
			$where .= " AND ip='{$ip}'";
		}
		$rs = SQL::share('collect_log')->where($where)->sort('id DESC')
			->setpages(compact('content', 'ip'))->isezr()->pagesize(50)->find();
		$this->smarty->assign('rs', $rs);
		$this->smarty->assign('page', SQL::share()->page);
		$this->display();
	}

	public function log_details() {
        $id = $this->request->get('id');
        $rs = SQL::share('collect_log')->where("id='{$id}'")->row();
        $this->smarty->assign('rs', $rs);
        $this->display();
    }



}
